<template>
  <div>
    <div id="barChart" ref="barChartRef" style="width: 600px; height: 400px"></div>
    <div id="pieChart" ref="pieChartRef" style="width: 600px; height: 400px"></div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import EChartsWrapper from '../utils/EChartsWrapper'

const chartWrapper = new EChartsWrapper()

export default defineComponent({
  name: 'ChartComponent',
  setup() {
    const barChartRef = ref<HTMLElement | null>(null)
    const pieChartRef = ref<HTMLElement | null>(null)

    // 柱状图初始化
    const initBarChart = () => {
      if (!barChartRef.value) return

      const chart = echarts.init(barChartRef.value)
      const data = [
        { name: '一月', value: 200 },
        { name: '二月', value: 150 },
        { name: '三月', value: 300 },
      ]

      const option = chartWrapper.getBarOption({
        data,
        title: {
          text: '月度销售额',
          color: '#333',
          position: 'left',
        },
        xAxis: {
          name: '月份',
          nameTextStyle: {
            color: '#666',
          },
        },
        yAxis: {
          name: '销售额',
          nameTextStyle: {
            color: '#666',
          },
        },
        // 自定义配置会与默认配置深度合并
        customOption: {
          tooltip: {
            formatter: '{b}: {c}',
          },
          series: [
            {
              barWidth: 20,
              itemStyle: {
                borderRadius: [4, 4, 0, 0],
              },
            },
          ],
        },
      })

      chart.setOption(option)
    }

    // 饼图初始化
    const initPieChart = () => {
      if (!pieChartRef.value) return

      const chart = echarts.init(pieChartRef.value)
      const data = [
        { name: '分类1', value: 335 },
        { name: '分类2', value: 310 },
        { name: '分类3', value: 234 },
      ]

      const option = chartWrapper.getPieOption({
        data,
        title: true,
        radius: ['40%', '70%'],
        position: {
          left: '10%',
          top: '10%',
        },
        // 自定义配置
        customOption: {
          legend: {
            orient: 'vertical',
            right: '10%',
            top: 'center',
          },
          series: [
            {
              label: {
                show: true,
                formatter: '{b}: {d}%',
              },
            },
          ],
        },
      })

      chart.setOption(option)
    }

    onMounted(() => {
      initBarChart()
      initPieChart()
    })

    return {
      barChartRef,
      pieChartRef,
    }
  },
})
</script>
